package net.huashitong.user.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.sirdc.modules.core.exceptions.ServiceException;
import com.sirdc.modules.utils.ObjectUtils;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.user.entity.SecurityToken;
import net.huashitong.user.filter.LoginFilter;
import net.huashitong.user.service.BnpUserService;
import net.huashitong.user.service.UserService;
import net.huashitong.user.utils.RegularExpressionsUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.databean.SysUserDataBean;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.service.SysUserService;
import com.sirdc.modules.utils.StringUtils;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;

/**
 * 用户模块接口
 *
 * @author <a href="mailto:yhy23456@163.com">huiyang.yu</a>
 * @since 2017.09.04
 */
@Controller
@RequestMapping("/api/user/")
public class UserController extends JsonBaseController {

    private UserService userService;
    private SysUserService sysUserService;
    private final static String apiKey= "b3232c91e3336d52ae80b73bb0a1cb912";	//关闭
//    private final static String apiKey= "b3232c91e3336d52ae80b73bb0a1cb91";

	@Autowired
	 private BnpUserService bus;
    @Autowired
    public UserController(UserService userService,SysUserService sysUserService) {
        this.userService = userService;
        this.sysUserService = sysUserService;
    }

   
    @Override
    protected String getView(String s) {
        return null;
    }

    /**
     * 登录
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Message login(@RequestParam String mobile,@RequestParam String validCode) {
    	try {
    		LoginFilter filter = new LoginFilter();
    		filter.setMobile(mobile);
    		filter.setValidCode(validCode);
    		//短信验证码校验
        	userService.validCode(filter);
    		SecurityToken token = userService.saveLogin(filter);
    		//SysUserDataBean user = sysUserService.getUserDataBeanById(token.getUserId());
    		BnpUser bu=  bus.getById(token.getUserId());
    		Map<String, Object> map = new HashMap<String, Object>();
	        map.put("userId", token.getUserId());
	        map.put("token", token.getToken());
	        map.put("userName", bu.getName());
	        map.put("branch", bu.getBranch());
	        map.put("role", bu.getRole());
	        map.put("sysId",bu.getSysId());
	        map.put("timestamp", Long.toString(System.currentTimeMillis()));
	        return coverMessage("200", "获取成功", map);
		} catch (Exception e) {
			return coverMessage("500",e.getMessage());
		}
    }
    @ResponseBody
    @RequestMapping(value = "/loginBypasw", method = RequestMethod.POST)
    public Message loginBypasw(@RequestParam String mobile,@RequestParam String password) {
    	try {
    		LoginFilter filter = new LoginFilter();
    		filter.setMobile(mobile);
    		
    		//短信验证码校验
    		SecurityToken token = userService.saveLogin(filter);
    		SysUserDataBean user = sysUserService.getUserDataBeanById(token.getUserId());
    		
    		Map<String, Object> map = new HashMap<String, Object>();
	        map.put("userId", token.getUserId());
	        map.put("token", token.getToken());
	        map.put("userName", user.getName());
	        map.put("timestamp", Long.toString(System.currentTimeMillis()));
	        if(password.equals("123456")){
	        	return coverMessage("200", "获取成功", map);
	        }else{
	        	return coverMessage("500", "账号或密码错误", map);
	        }
	        
		} catch (Exception e) {
			return coverMessage("500",e.getMessage());
		}
    }
   /* @ResponseBody
    @RequestMapping(value = "/loginByPasw", method = RequestMethod.POST)
    public Message loginByPasw(@RequestParam String mobile,@RequestParam String password) {
    	try {
    		LoginFilter filter = new LoginFilter();
    		filter.setMobile(mobile);
        	userService.validCode(filter);
    		SecurityToken token = userService.saveLogin(filter);
    		SysUserDataBean user = sysUserService.getUserDataBeanById(token.getUserId());
    		
    		Map<String, Object> map = new HashMap<String, Object>();
	        map.put("userId", token.getUserId());
	        map.put("token", token.getToken());
	        map.put("userName", user.getName());
	        map.put("timestamp", Long.toString(System.currentTimeMillis()));
	        
	        return coverMessage("200", "获取成功", map);
		} catch (Exception e) {
			return coverMessage("500",e.getMessage());
		}
    }*/
    /**
     * 发送验证码
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping("/sendValidCode")
    public Message sendValidCode(@RequestParam String mobile){
    	LoginFilter filter = new LoginFilter();
    	filter.setMobile(mobile);
    	if (StringUtils.isBlank(filter.getMobile())
				|| !RegularExpressionsUtils.phone(filter.getMobile())) {
			return coverMessage("500", "参数有误，请重新输入");
		}
		if (!userService.queryByMobile(filter.getMobile())) {
			return coverMessage("500", "用户不存在");
		}
		String validCode = Integer.toString((int)((Math.random()*9+1)*1000));
    	YunpianClient clnt = new YunpianClient(apiKey).init();
    	//修改账户信息API
    	Map<String, String> param = clnt.newParam(2);
    	param.put(YunpianClient.MOBILE, filter.getMobile());
    	param.put(YunpianClient.TEXT, "【重大项目节点管理】您的验证码是"+validCode+"。如非本人操作，请忽略本短信");
    	Result<SmsSingleSend> r = clnt.sms().single_send(param);
    	//获取返回结果，返回码:r.getCode(),返回码描述:r.getMsg(),API结果:r.getData(),其他说明:r.getDetail(),调用异常:r.getThrowable()
    	//账户:clnt.user().* 签名:clnt.sign().* 模版:clnt.tpl().* 短信:clnt.sms().* 语音:clnt.voice().* 流量:clnt.flow().* 隐私通话:clnt.call().*
    	//最后释放client
    	clnt.close();
    	userService.saveValid(filter.getMobile(),validCode);
    	if(r.getCode()!=0){
    		return coverMessage("500", "短信验证码获取失败");
    	}
		return coverMessage("200", "短信验证码发送成功");
    }

	@ResponseBody
	@RequestMapping(value = "/newlogin", method = RequestMethod.POST)
	public Message newlogin(@RequestBody LoginFilter filter) {
		try {
			BnpUser bu=null;
			//短信验证码校验
			if(ObjectUtils.isNotBlank(filter.getValidCode())){
				userService.validCode(filter);
				bu=bus.getBnpUserByPhone(filter.getMobile());
			}else {
                bu=bus.getBnpUser(filter.getMobile(),filter.getPassword());
			}
			if(ObjectUtils.isNotBlank(bu)) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("userId", bu.getSysId());
				map.put("token", userService.getToken());
				map.put("userName", bu.getName());
				map.put("branch", bu.getBranch());
				map.put("branchType",bu.getBranchType());
				map.put("role", bu.getRole());
				map.put("timestamp", Long.toString(System.currentTimeMillis()));
				return coverMessage("200", "获取成功", map);
			}else{
				throw new ServiceException("用户不存在或者密码错误！");
			}

		} catch (Exception e) {
			return coverMessage("500",e.getMessage());
		}
	}
}
